package leetcode.f1t100;

/**
 * 实现math.power(x,n)
 * https://leetcode.com/problems/powx-n/
 *
 * @Author lichongxiao
 * @Date 2022/10/24 19:49
 */
public class Q50_PowXN {
    public double myPow(double x, int n) {
        if (n == 0) {
            return 1d;
        }
        double ans = 1d;
        int pow = Math.abs(n == Integer.MIN_VALUE ? n + 1 : n);
        for (int i = 0; i < pow; i++) {
            ans *= x;
        }
        if(n == Integer.MIN_VALUE){
            ans*=x;
        }
        return n > 0 ? ans : 1d /ans;
    }

    public double myPow1(double x, int n){
        if (n == 0) {
            return 1d;
        }
        double ans = 1d, t = x;
        int pow = Math.abs(n == Integer.MIN_VALUE ? n + 1 : n);
        while(pow != 0){
            if((pow & 1) != 0){
                ans *= t;
            }
            pow >>= 1;
            t *= t;
        }
        if(n == Integer.MIN_VALUE){
            ans*=x;
        }
        return n > 0 ? ans : 1d /ans;
    }

    public static void main(String[] args) {
        Q50_PowXN bean = new Q50_PowXN();
        System.out.println(bean.myPow(0.1,3));
        System.out.println(bean.myPow1(0.1,3));
        System.out.println(bean.myPow(0.1,-3));
        System.out.println(bean.myPow1(0.1,-3));
    }
}
